package cn.yuitstyle.fss.minio.starter.util;

import io.minio.*;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @author yuwg
 */
@Component
public class MinioBucketUtils {


    @Autowired
    private MinioClient minioClient;

    /**
     * 创建 bucket
     * @param bucketName bucketName
     */
    @SneakyThrows
    private void createBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs
                    .builder()
                    .bucket(bucketName)
                    .build()
            );
        }
    }

    /**
     * 判断bucket是否存在 存在 true 不存在 false
     * @param bucketName bucketName
     */
    @SneakyThrows
    public boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName).build());
    }

    /**
     * 获取bucket策略
     * @param bucketName bucketName
     */
    @SneakyThrows
    public String getBucketPolicy(String bucketName) {
        return minioClient.getBucketPolicy(GetBucketPolicyArgs.builder()
                .bucket(bucketName).build());
    }

    /**
     * 获得所有Bucket列表
     */
    @SneakyThrows
    public List<Bucket> getAllBuckets() {
        return minioClient.listBuckets();
    }

    /**
     *  根据bucketName获取其相关信息
     * @param bucketName bucketName
     */
    @SneakyThrows
    public Optional<Bucket> getBucket(String bucketName) {
        return getAllBuckets().stream().filter(bucket -> bucket.name().equals(bucketName)).findFirst();
    }

    /**
     * 根据bucketName删除Bucket，true：删除成功； false：删除失败，文件或已不存在
     * @param bucketName bucketName
     */
    @SneakyThrows
    public void removeBucket(String bucketName) {
        minioClient.removeBucket(RemoveBucketArgs.builder()
                .bucket(bucketName)
                .build());
    }

}
